#Region "Using directives"
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports C4F.DevKit.Messaging
#End Region
Namespace MapiApplication
	Public Partial Class MailClient
	Inherits Form
		#Region "Globals"
		Private objMapiManager As MapiManager = New MapiManager()
		Private mails As List(Of Mail) = New List(Of Mail)()
		Private toolTipToNames As String = String.Empty
		Private toolTipCcNames As String = String.Empty
		Private toolTipAttachmentNames As String = String.Empty
		Private toolTipSubjectNames As String = String.Empty
		Private toolTipFromNames As String = String.Empty
        Private tp As ToolTip = New ToolTip()
        Private credentialList As List(Of String) = New List(Of String)
		#End Region
		#Region "Constructors"
		Public Sub New()
		End Sub
		Public Sub New(ByVal profileName As String)
			InitializeComponent()
			AddColumnsToGrid()
			SetColumnsWidth()
			Try
				objMapiManager.Logon(profileName)
				GetAllMails()
			Catch mapiManagerException As MapiManagerException
				MessageBox.Show(mapiManagerException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.[Error])
			Catch invalidOperationException As InvalidOperationException
				MessageBox.Show(invalidOperationException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.[Error])
			Catch argException As ArgumentException
				MessageBox.Show(argException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.[Error])
			End Try
		End Sub
		#End Region
		#Region "Helper Methods"
		Private Sub AddColumnsToGrid()
			dgInbox.Columns.Add("Id", "Id")
			dgInbox.Columns.Add("From", "From")
			dgInbox.Columns.Add("Subject", "Subject")
			dgInbox.Columns.Add("Received", "Received")
		End Sub
		Private Sub SetColumnsWidth()
			Try
				Dim colCount As Integer = dgInbox.ColumnCount - 1
				If colCount <> 0 Then
                    Dim colWidth As Integer = CType(((dgInbox.Width) / colCount), Integer)
					For Each d As DataGridViewColumn In dgInbox.Columns
						d.Width = colWidth
					Next
				End If
			Catch ex As Exception
				MessageBox.Show(ex.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.[Error])
			End Try
		End Sub
		Private Sub DeleteMail()
			Try
				Dim row As DataGridViewSelectedRowCollection = dgInbox.SelectedRows
				For Each r As DataGridViewRow In row
					Dim id As String = r.Cells(0).Value.ToString()
					objMapiManager.DeleteMail(id)
					dgInbox.Rows.Remove(r)
				Next
			Catch mapiException As MapiManagerException
				MessageBox.Show(mapiException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.[Error])
			Catch argNullException As ArgumentNullException
				MessageBox.Show(argNullException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.[Error])
			Catch argException As ArgumentException
				MessageBox.Show(argException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.[Error])
			End Try
		End Sub
		Private Sub GetMailDetails()
			Dim row As DataGridViewSelectedRowCollection = dgInbox.SelectedRows
			For Each r As DataGridViewRow In row
				If r.Cells("Id").Value IsNot Nothing Then
					Dim id As String = r.Cells("Id").Value.ToString()
					For Each m As Mail In mails
						If m.Id = id Then
							lblfrom.Text = DisplayText(m.From)
							toolTipFromNames = m.From
							Dim toNames As String = GetNames(m.ToList)
							lblTo.Text = DisplayText(toNames)
							toolTipToNames = toNames
							lblSubject.Text = DisplayText(m.Subject)
							toolTipSubjectNames = m.Subject
							Dim ccNames As String = GetNames(m.CcList)
							lblCc.Text = DisplayText(ccNames)
							toolTipCcNames = ccNames
							txtMailBody.Text = m.MessageBody
							FillAttachCombo(m.Attachments)
						End If
					Next
				End If
			Next
		End Sub
		Private Sub FillAttachCombo(ByVal list As List(Of String))
			cmbAttachments.Items.Clear()
			Dim attachmentNull As Boolean = False
			If list IsNot Nothing Then
				For Each attachment As String In list
					If attachment Is Nothing Then
						attachmentNull = True
					Else
						cmbAttachments.Items.Add(attachment)
					End If
				Next
				If attachmentNull Then
					cmbAttachments.Enabled = False
					btnSave.Enabled = False
				Else
					cmbAttachments.SelectedIndex = 0
					cmbAttachments.Enabled = True
					btnSave.Enabled = True
				End If
			Else
				cmbAttachments.Enabled = False
				btnSave.Enabled = False
			End If
		End Sub
		Private Sub ToolTipDisplay(ByVal ctl As Control, ByVal s As String)
			tp.RemoveAll()
			tp.SetToolTip(ctl, s)
		End Sub
		Private Function DisplayText(ByVal str As String) As String
			Dim returnString As String = String.Empty
			Dim limit As Integer = 35
			If str IsNot Nothing Then
				If str.Length > limit Then
					returnString = str.Substring(0, limit - 3)
					returnString += "..."
				Else
					Return str
				End If
			End If
			Return returnString
		End Function
		Private Function GetNames(ByVal list As List(Of String)) As String
			Dim names As String = String.Empty
			If list IsNot Nothing Then
				If list.Count > 1 Then
					Dim i As Integer = 0
					While i < list.Count - 1
						names += list(i)
						names += ";"
						i += 1
					End While
					names += list(i)
				End If
				If list.Count = 1 Then
					names = list(0)
				End If
			End If
			Return names
		End Function
		Private Sub GetAllMails()
			Try
				mails = objMapiManager.GetAvailableMails()
				For Each m As Mail In mails
					dgInbox.Rows.Add(m.Id, m.From, m.Subject, m.[Date])
				Next
				dgInbox.Columns("Id").Visible = False
			Catch mapimanagerException As MapiManagerException
				MessageBox.Show(mapimanagerException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.[Error])
			End Try
		End Sub
		#End Region
		#Region "Event Handlers"
        Private Sub MailClient_FormClosed(ByVal sender As Object, ByVal e As FormClosedEventArgs) Handles MyBase.FormClosed
            Try
                objMapiManager.Logoff()
            Catch mapimanagerException As MapiManagerException
                MessageBox.Show(mapimanagerException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.[Error])
            Catch invalidOperation As InvalidOperationException
                MessageBox.Show(invalidOperation.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.[Error])
            End Try
        End Sub
        Private Sub dgInbox_SizeChanged(ByVal sender As Object, ByVal e As EventArgs) Handles dgInbox.SizeChanged
            SetColumnsWidth()
        End Sub
        Private Sub toolStripCreateNew_Click(ByVal sender As Object, ByVal e As EventArgs) Handles toolStripCreateNew.Click
            Dim objCreateNew As frmCreateNew = New frmCreateNew(objMapiManager, credentialList)
            objCreateNew.Show()
        End Sub
        Private Sub toolStripDelete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles toolStripDelete.Click
            DeleteMail()
        End Sub
        Private Sub dgInbox_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs) Handles dgInbox.SelectionChanged
            GetMailDetails()
        End Sub
        Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles MyBase.KeyDown
            If e.KeyCode = Keys.Delete Then
                DeleteMail()
            End If
            If e.KeyCode = Keys.Escape Then
                Me.Close()
            End If
        End Sub
        Private Sub toolStripBtnReply_Click(ByVal sender As Object, ByVal e As EventArgs) Handles toolStripBtnReply.Click
            Dim objCreateNew As frmCreateNew = New frmCreateNew(objMapiManager, lblfrom.Text, String.Empty, "Re: " + lblSubject.Text, txtMailBody.Text)
            objCreateNew.Show()
        End Sub
        Private Sub toolStripBtnReplyAll_Click(ByVal sender As Object, ByVal e As EventArgs) Handles toolStripBtnReplyAll.Click
            Dim replyToList As String = String.Empty
            Dim replyCcList As String = String.Empty
            Dim row As DataGridViewSelectedRowCollection = dgInbox.SelectedRows
            For Each r As DataGridViewRow In row
                If r.Cells("Id").Value IsNot Nothing Then
                    Dim id As String = r.Cells("Id").Value.ToString()
                    For Each m As Mail In mails
                        If m.Id = id Then
                            If m.From.EndsWith(";") Then
                                replyToList = m.From + GetNames(m.ToList)
                            Else
                                replyToList = m.From + ";" + GetNames(m.ToList)
                            End If
                            replyCcList = GetNames(m.CcList)
                            Dim objCreateNew As frmCreateNew = New frmCreateNew(objMapiManager, replyToList, replyCcList, "Re: " + m.Subject, txtMailBody.Text)
                            objCreateNew.Show()
                        End If
                    Next
                End If
            Next
        End Sub
        Private Sub toolStripBtnRefresh_Click(ByVal sender As Object, ByVal e As EventArgs) Handles toolStripBtnRefresh.Click
            dgInbox.Rows.Clear()
            GetAllMails()
        End Sub
        Private Sub lblfrom_MouseHover(ByVal sender As Object, ByVal e As EventArgs) Handles lblfrom.MouseHover
            ToolTipDisplay(DirectCast(sender, Control), toolTipFromNames)
        End Sub
        Private Sub lblTo_MouseHover(ByVal sender As Object, ByVal e As EventArgs) Handles lblTo.MouseHover
            ToolTipDisplay(DirectCast(sender, Control), toolTipToNames)
        End Sub
        Private Sub lblSubject_MouseHover(ByVal sender As Object, ByVal e As EventArgs) Handles lblSubject.MouseHover
            ToolTipDisplay(DirectCast(sender, Control), toolTipSubjectNames)
        End Sub
        Private Sub lblCc_MouseHover(ByVal sender As Object, ByVal e As EventArgs) Handles lblCc.MouseHover
            ToolTipDisplay(DirectCast(sender, Control), toolTipCcNames)
        End Sub
        Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
            Dim saveFileDialog As FolderBrowserDialog = New FolderBrowserDialog()
            Dim rows As DataGridViewSelectedRowCollection = dgInbox.SelectedRows
            saveFileDialog.Description = "Please select path to save the file:"
            saveFileDialog.ShowNewFolderButton = True
            If saveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
                Try
                    Dim targetPath As String = saveFileDialog.SelectedPath
                    objMapiManager.SaveAttachment(rows(0).Cells("Id").Value.ToString(), cmbAttachments.SelectedIndex, targetPath + "\", cmbAttachments.Text, False)
                Catch mapiException As MapiManagerException
                    MessageBox.Show(mapiException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                Catch argNullException As ArgumentNullException
                    MessageBox.Show(argNullException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                Catch argException As ArgumentException
                    MessageBox.Show(argException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                End Try
            End If
        End Sub
		#End Region

       
    End Class
End Namespace
